package br.gfca.lanhostfinder;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunnableHostFinder implements Runnable {

	private boolean[] foundHosts;
	private String hostAddr;
	private int timeout;
	
	public RunnableHostFinder(boolean[] foundHosts, String hostAddr, int timeout) {
		this.foundHosts = foundHosts;
		this.hostAddr = hostAddr;
		this.timeout = timeout;		
	}
	
	@Override
	public void run() {
		this.foundHosts[this.getIndex()] = this.found();
	}
	
	private boolean found() {
		try {
			Process p = Runtime.getRuntime().exec(new String[]{"ping", "-n", "1", "-w", "" + this.timeout, this.hostAddr});
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			
			br.readLine();
			br.readLine();
			br.readLine();
			br.readLine();
			br.readLine();
			br.readLine();
			String linha = br.readLine();
			
			boolean b = linha.indexOf("Resposta") != -1;
			if ( b ) {
				System.out.println("Found host: " + this.hostAddr);
			}
			return b; 
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private int getIndex() {
		return Integer.parseInt(this.hostAddr.substring( this.hostAddr.lastIndexOf(".") + 1 ));
	}
	
}
